import { getUserInfoAPI, loginAPI } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes
}

const mutations = {
  saveToken(state, playLoad) {
    state.token = playLoad
  },
  saveUser(state, playLoad) {
    state.userInfo = playLoad
  },
  setRoutes(state, playLoad) {
    state.routes = [...constantRoutes, ...playLoad]
  }
}

const actions = {
  async loginAction(store, playLoad) {
    const res = await loginAPI(playLoad)
    console.log(res)
    setToken(res)
    store.commit('saveToken', res)
    router.push('/')
    Message({
      type: 'success',
      message: '登录成功'
    })
  },
  async getUserInfoAction(store) {
    const res = await getUserInfoAPI()
    console.log('res  ----->  ', res)
    store.commit('saveUser', res)
  },
  async logoutAction(store) {
    store.commit('saveToken', '')
    store.commit('saveUser', {})
    router.push('/login')
    resetRouter() // 重置路由
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

